import json

from flask import request, jsonify, make_response

from app import app, mysql
from models import User, db, UserCoupon, Coupon, UserPoints, Mile


# 统一设置响应格式和字符集
def json_response(data, status=200):
    response = make_response(
        json.dumps(data, ensure_ascii=False),  # 确保不转义中文字符
        status
    )
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response


def error_response(msg):
    return {'code': 409, 'msg': '出现错误', 'data': msg}


@app.route('/')
def first_page():
    return json_response('welcome to yebosean\'s web'), 200


@app.route('/test-you')
def test():
    cur = mysql.connection.cursor()
    cur.execute("SELECT * FROM users ")
    products = cur.fetchall()[0]
    cur.close()
    return json_response({'code': 201, 'msg': '创建用户成功', 'data': products}, 200)


# 创建用户信息
@app.route('/driver/user-info', methods=['POST'])
def register():
    data = request.get_json()
    # 验证输入
    try:
        # 检查用户是否存在
        is_exist = User.query.filter_by(id=data['id']).first()
        if is_exist:
            return json_response({'code': 409, 'msg': data['name'] + '用户已存在', 'data': ''}, 409)
        # 使用 ORM 方式
        new_user = User(
            id=data['id'],
            name=data['name'],
            avatar=data['avatar'],
            phone=data['phone'],
            password=data['password'], )
        db.session.add(new_user)
        db.session.commit()
        response = jsonify({'code': 201, 'msg': '创建用户成功', 'data': ''})
        response.headers['content-type'] = 'application/json;charset=utf-8'
        return json_response({'code': 201, 'msg': '创建用户成功', 'data': {'name': 'xiao', 'age': '14'}}, 201)
    except Exception as e:
        return jsonify(error_response(e)), 500


@app.route('/driver/user-info/get-user', methods=['GET'])
def get_info():
    try:
        user_id = request.args.get('id')
        # 使用原始 SQL 方式
        cur = mysql.connection.cursor()
        cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
        products = cur.fetchall()[0]
        cur.close()
        return json_response({'code': 201, 'msg': '创建用户成功', 'data': products}, 200)
    except Exception as e:
        print('错误错误')
        print(str(e))
        return jsonify(error_response(e)), 500


@app.route('/driver/user-info/update-phone', methods=['PUT'])
def update_phone():
    try:
        user_id = request.args.get('id')
        new_phone = request.args.get('phone')
        cur = mysql.connection.cursor()
        cur.execute("UPDATE users set phone=%s WHERE id = %s", (new_phone, user_id,))
        cur.close()
        return json_response({'code': 201, 'msg': '电话修改成功', 'data': new_phone}, 201)
    except Exception as e:
        print('<UNK>')
        print(str(e))
        return jsonify(error_response(e)), 500


@app.route('/driver/user-info/update-password', methods=['PUT'])
def update_password():
    try:
        user_id = request.args.get('id')
        new_password = request.args.get('password')
        cur = mysql.connection.cursor()
        cur.execute("UPDATE users set password=%s WHERE id = %s", (new_password, user_id,))
        cur.close()
        return json_response({'code': 201, 'msg': '密码修改成功', 'data': new_password}, 201)
    except Exception as e:
        print('<UNK>')
        print(str(e))
        return jsonify(error_response(e)), 500


@app.route('/driver/user-info/update-name', methods=['PUT'])
def update_name():
    try:
        user_id = request.args.get('id')
        new_name = request.args.get('name')
        # print('name' + new_name)
        cur = mysql.connection.cursor()
        cur.execute("UPDATE users set name=%s WHERE id = %s", (new_name, user_id,))
        cur.close()
        return json_response({'code': 201, 'msg': '昵称修改成功', 'data': new_name}, 201)
    except Exception as e:
        print('<UNK>')
        print(str(e))
        return jsonify(error_response(e)), 500


# 更新头像
@app.route('/driver/user-info/update-avatar', methods=['PUT'])
def update_avatar():
    try:
        user_id = request.args.get('id')
        new_avatar = request.args.get('avatar')
        cur = mysql.connection.cursor()
        cur.execute("UPDATE users set avatar=%s WHERE id = %s", (new_avatar, user_id,))
        cur.close()
        return json_response({'code': 201, 'msg': '头像修改成功', 'data': new_avatar}, 201)
    except Exception as e:
        print('<UNK>')
        return json_response({'code': 500, 'msg': '服务器内部错误', 'data': str(e)}, 500)


# 获取用户积分
@app.route('/driver/user-info/get-user-points', methods=['GET'])
def get_user_points():
    try:
        user_id = request.args.get('user_id')
        if not user_id:
            return json_response({'code': 400, 'msg': '缺少用户ID'}, 400)
            # 查询用户积分
        user_points = UserPoints.query.filter_by(user_id=user_id).first()

        # 返回结果
        points = user_points.points if user_points else 0
        return json_response({
            'code': 200,
            'msg': '成功',
            'data': points
        }, 200)
    except Exception as e:
        print('<UNK>')
        return json_response({'code': 500, 'msg': '服务器内部错误', 'data': str(e)}, 500)


# 创建积分账户
@app.route('/driver/user-info/user-points', methods=['PUT'])
def user_points():
    try:
        user_id = request.args.get('id')
        points = request.args.get('points')
        cur = mysql.connection.cursor()
        # 检查用户是否存在
        cur.execute('SELECT * FROM user_points WHERE user_id= %s', (user_id,))
        result = cur.fetchall()
        print(result)
        if len(result) > 0:
            return json_response({'code': 409, 'msg': '用户已存在', 'data': ''}, 409)

        cur.execute("insert into user_points(user_id,points) values (%s,%s)", (user_id, points))
        cur.close()
        return json_response({'code': 201, 'msg': '积分账户修改成功', 'data': ''}, 201)
    except Exception as e:
        print('<UNK>')
        return json_response({'code': 500, 'msg': '服务器内部错误', 'data': str(e)}, 500)


# 获取所有可兑换的优惠券
@app.route('/driver/user-info/get-coupon', methods=['GET'])
def get_coupon():
    try:
        cur = mysql.connection.cursor()
        # 检查用户是否存在
        cur.execute('SELECT * FROM coupon ')
        result = cur.fetchall()
        cur.close()
        return json_response({'code': 201, 'msg': '积分账户修改成功', 'data': result}, 201)
    except Exception as e:
        print('<UNK>')
        return json_response({'code': 500, 'msg': '服务器内部错误', 'data': str(e)}, 500)


# 添加用户优惠券
@app.route('/driver/user-info/add-coupon', methods=['POST'])
def add_coupon():
    data = request.get_json()
    user_id = data.get('user_id')
    coupon_id = data.get('coupon_id')

    if not user_id or not coupon_id:
        return json_response({'code': 400, 'msg': '缺少用户或优惠券', 'data': ''}, 400)

    try:
        # 检查优惠券是否存在
        coupon = Coupon.query.get(coupon_id)
        if not coupon:
            return json_response({'code': 404, 'msg': '找不到优惠券', 'data': ''}, 404)

        # 创建用户优惠券关联
        user_coupon = UserCoupon(
            user_id=user_id,
            coupon_id=coupon_id
        )

        db.session.add(user_coupon)
        db.session.commit()
        return json_response({'code': 201, 'msg': '兑换成功', 'data': ''}, 201)

    except Exception as e:
        db.session.rollback()
        return json_response({'code': 500, 'msg': '服务器内部错误', 'data': str(e)}, 500)


# 获取用户的优惠券列表
@app.route('/driver/user-coupons/<user_id>', methods=['GET'])
def get_user_coupons(user_id):
    try:
        # 获取用户的所有优惠券关联
        user_coupons = UserCoupon.query.filter_by(user_id=user_id).all()

        # 转换为包含优惠券详细信息的字典列表
        coupons_data = [uc.to_dict() for uc in user_coupons]

        return json_response({'code': 201, 'msg': '获取成功', 'data': coupons_data}, 201)

    except Exception as e:
        return json_response({'code': 500, 'msg': '服务器内部错误', 'data': str(e)}, 500)


# 增加积分
@app.route('/driver/points/add-points', methods=['POST'])
def add_points():
    data = request.get_json()
    user_id = data.get('user_id')
    points = data.get('points')

    if not user_id or not points:
        return json_response({'code': 400, 'msg': '缺少参数', 'data': ''}, 400)

    try:
        # 检查用户是否存在
        user_exist = UserPoints.query.filter_by(user_id=user_id).first()
        if not user_exist:
            return json_response({'code': 404, 'msg': '找不到用户', 'data': ''}, 404)

        # 查询或创建用户积分记录
        user_exist.points += points
        db.session.commit()
        return json_response({'code': 201, 'msg': '修改成功', 'data': user_exist.to_dict()}, 201)

    except Exception as e:
        db.session.rollback()
        return json_response({'code': 500, 'msg': '服务器内部错误', 'data': str(e)}, 500)


# 消耗积分
@app.route('/driver/points/reduce-points', methods=['POST'])
def reduce_points():
    data = request.get_json()
    user_id = data.get('user_id')
    points = data.get('points')

    if not user_id or not points:
        return json_response({'code': 400, 'msg': '缺少参数', 'data': ''}, 400)

    try:
        # 检查用户是否存在
        user_exist = UserPoints.query.filter_by(user_id=user_id).first()
        if not user_exist:
            return json_response({'code': 404, 'msg': '找不到用户', 'data': ''}, 404)

        # 查询或创建用户积分记录
        user_exist.points -= points
        db.session.commit()
        return json_response({'code': 201, 'msg': '修改成功', 'data': user_exist.to_dict()}, 201)

    except Exception as e:
        db.session.rollback()
        return json_response({'code': 500, 'msg': '服务器内部错误', 'data': str(e)}, 500)


# 获取公里数
@app.route('/driver/user-info/get-miles', methods=['GET'])
def get_miles():
    try:
        user_id = request.args.get('user_id')
        if not user_id:
            return json_response({'code': 400, 'msg': '缺少用户ID', 'data': 'user_id 参数不能为空'}, 400)
            # 查询用户积分
        mile = Mile.query.get(user_id)
        if not mile:
            mile = Mile(user_id=user_id, miles=0)
            db.session.add(mile)
            db.session.commit()
        # 返回结果

        return json_response({
            'code': 200,
            'msg': '成功',
            'data': mile.miles
        }, 200)
    except Exception as e:
        print('<UNK>')
        return json_response({'code': 500, 'msg': '服务器内部错误', 'data': str(e)}, 500)


# 更新公里数
@app.route('/driver/user-info/update-miles', methods=['PUT'])
def update_miles():
    try:
        user_id = request.args.get('user_id')
        miles = request.args.get('miles')
        if not user_id:
            return json_response({'code': 400, 'msg': '缺少用户ID'}, 400)
        # 查询是否存在用户
        mile = Mile.query.filter_by(user_id=user_id).first()
        if not mile:
            return json_response({'code': 404, 'msg': '用户不存在', 'data': ''}, 404)
        mile.miles = miles
        db.session.commit()
        return json_response({
            'code': 200,
            'msg': '成功',
            'data': ''
        }, 200)
    except Exception as e:
        print('<UNK>')
        return json_response({'code': 500, 'msg': '服务器内部错误', 'data': str(e)}, 500)
